package com.commonEncryptionAlgorithms.hashFunction.hash.SHA;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class SHA_256Example {
    public static void main(String[] args) {
        String password = "mypassword";
        
        // 生成随机盐值
        byte[] salt = generateSalt();
        
        // 将密码和盐值组合在一起
        String saltedPassword = password + Base64.getEncoder().encodeToString(salt);
        
        // 对组合后的密码进行SHA-256加密
        String hashedPassword = hashPassword(saltedPassword);
        
        System.out.println("Salted and hashed password: " + hashedPassword);
    }
    
    private static byte[] generateSalt() {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return salt;
    }
    
    private static String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest(password.getBytes());
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
